"use client";

import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ColDef } from "ag-grid-community";
import DataGrid from "@/components/data-grid";
import { useQuery } from "@tanstack/react-query";
import { CustomCellRendererProps } from "ag-grid-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
const CookiePage = () => {
  const queryClient = useQueryClient();

  const [rowData, setRowData] = useState<{}[]>([]);
  const cookieQuery = useQuery({
    queryKey: ["cookies"],
    queryFn: () =>
      fetch(`/api/cookies/list`, {
        method: "GET",
        //credentials: "include",
      }).then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          setRowData([]);
        }
      }),
  });
  const ActionsRender = (params: CustomCellRendererProps) => {
    return (
      <Button
        variant={"link"}
        onClick={() => {
          const { data } = params;
          fetch(`/api/cookies/${data.id}`, { method: "DELETE" })
            .then((resp) => {
              if (resp.ok) {
                queryClient.invalidateQueries({ queryKey: ["cookies"] });
                toast.info(`Cookie ${data.name} delete successfully`);
              } else {
                toast.error(`Delete ${data.name} faild`);
              }
            })
            .catch((err) => {
              toast.error(`Exception Delete failed ${data.name} error:${err}`);
            });
        }}
      >
        删除
      </Button>
    );
  };

  useEffect(() => {
    if (cookieQuery.isPending || !cookieQuery.data) return;
    setRowData(cookieQuery.data);
  }, [cookieQuery]);
  const columnDefs: ColDef[] = [
    { field: "id", headerName: "ID", width: 100 },
    { field: "name", headerName: "Name", flex: 1 },
    { field: "filename", headerName: "FileName", flex: 1 },
    { field: "content", headerName: "Content", flex: 1 },
    { field: "platformName", headerName: "PlatformName", flex: 1 },
    {
      field: "actions",
      headerName: "Actions",
      flex: 1,
      cellRenderer: ActionsRender,
    },
  ];
  return <DataGrid columnDefs={columnDefs} rowData={rowData} />;
};
export default CookiePage;
